/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.mycompany.delivery.rest;

import com.mycompany.delivery.dto.DeliveryDTO;
import com.mycompany.delivery.dto.UserDTO;
import static com.mycompany.delivery.rest.ContactRestController.log;
import com.mycompany.delivery.service.AccountServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.mycompany.delivery.servicelayer.DeliveryService;
import com.mycompany.delivery.servicelayer.UserService;
import java.util.ArrayList;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;


/**
 *
 * @author Jana Němcová
 */
@RestController
@RequestMapping("/deliveries")
public class DeliveryRestController 
{
    final static Logger log = LoggerFactory.getLogger(DeliveryRestController.class);
    
    @Autowired
    private DeliveryService deliveryService;
    
    @Autowired UserService userService;
    
    @Autowired
    @Qualifier("accUserDetailsService")
    private AccountServiceImpl accUserDetailsService;

    
    @RequestMapping(value = "getDeliveries", headers = "Accept=text/plain")
    public String getDeliveries()
    {
        LoginCheck();
        String del = "";
        
        for(DeliveryDTO d : deliveryService.getDeliveriesInUnprocessedState())
        {
            del += " " + d;
        }
        
        return del;
    }
    
    
    public void LoginCheck() {
         Authentication auth = SecurityContextHolder.getContext().getAuthentication();
         if(auth == null || !"rest".equals(auth.getName())) {
              UserDetails userDetails = accUserDetailsService.loadUserByUsername("rest");
            Authentication authentication = new UsernamePasswordAuthenticationToken(
                    userDetails, userDetails.getPassword(), userDetails.getAuthorities());
            SecurityContextHolder.getContext().setAuthentication(authentication);
            log.debug("rest loged");
         }else {
             log.debug("loged");
         }
    }

    @RequestMapping(value = "getDelivery/{id}", method = RequestMethod.GET, headers = "Accept=text/plain")
    public String getDelivery(@PathVariable("id") Long id)
    {
        LoginCheck();
        return (deliveryService.find(id)).toString();
    }
    
    
    @RequestMapping(value = "getDeliveryJson/{id}", method = RequestMethod.GET, headers ="Accept=application/json; charset=UTF-8")
    public DeliveryDTO getDeliveryAsJSON(@PathVariable("id") Long id)
    {
        LoginCheck();
        return deliveryService.find(id);
    }
    
    @RequestMapping(value = "/getAllDeliveriesWithoutCourierJson", method = RequestMethod.GET, headers = "Accept=application/json; charset=UTF-8")
    public List<DeliveryDTO> getDeliveriesWithoutCourierJSON() {
        LoginCheck();
        return deliveryService.getDeliveriesWithoutCourier();
    }
    
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    @ResponseBody
    public DeliveryDTO update(@RequestBody DeliveryDTO delivery) {
        LoginCheck();
        DeliveryDTO returnDelivery;
        if(delivery.getId()==null||delivery.getId()== 0) {
           returnDelivery = deliveryService.create(delivery);
        }else {
            returnDelivery = deliveryService.update(delivery);
        }
        return  returnDelivery;
    }
     
    @RequestMapping(value="getCouriersJson", method = RequestMethod.GET, headers = "Accept=application/json; charset=UTF-8")
    public List<UserDTO> getCouriersAsJson()
    {
        LoginCheck();
        return userService.getAllCouriers();
    }
    
    @RequestMapping(value="getCurrentDeliveriesJson", method = RequestMethod.GET, headers = "Accept=application/json; charset=UTF-8")
    public List<DeliveryDTO> getCurrentDeliveriesJson()
    {
        LoginCheck();
        List<DeliveryDTO> del = new ArrayList<>();
        for(DeliveryDTO d : deliveryService.getDeliveriesInProcessedState())
        {
            del.add(d);
        }
        for(DeliveryDTO d : deliveryService.getDeliveriesInUnprocessedState())
        {
            del.add(d);
        }
        
        return del;
    }
    
    
    @RequestMapping(value="addDeliveryToCourier/{id}", method = RequestMethod.POST)
    @ResponseBody
    public DeliveryDTO addDeliveryToCourier(@RequestBody DeliveryDTO delivery, @PathVariable("id") Long courierId) 
    {
        deliveryService.addDeliveryToCourier(deliveryService.find(delivery.getId()), userService.findCourier(courierId));
        return deliveryService.find(delivery.getId());
    }
    

    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    @ResponseBody
    public DeliveryDTO delete(@RequestBody DeliveryDTO delivery) {
        return  deliveryService.remove(delivery);
    }
}
